<template>
  <div class="ad-management-layout">
    <!-- 左侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header" @click="router.push('/')">
        <h2>DevPlatform</h2>
      </div>

      <el-menu
          :default-active="activeMenu"
          class="sidebar-menu"
          @select="handleMenuSelect"
      >
        <el-menu-item index="statistics">数据统计</el-menu-item>
        <el-menu-item index="merchant">广告商</el-menu-item>
        <el-menu-item index="review">广告审核</el-menu-item>
      </el-menu>
    </div>

    <!-- 右侧内容区域 -->
    <div class="main-content">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>{{ pageTitle }}</h1>
      </div>

      <!-- 内容区域 -->
      <!-- 数据统计 -->
      <div v-show="activeTab === 'statistics'" class="tab-content">
        <el-card class="ad-card">
          <div slot="header">
            <h2>广告数据统计</h2>
          </div>

          <div class="stats-filter">
            <el-date-picker
                v-model="dateRange"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                range-separator="至"
                start-placeholder="开始日期"
                type="daterange"
                value-format="YYYY-MM-DD"
            ></el-date-picker>

            <el-select
                v-model="statsFilter.position"
                class="position-select"
                placeholder="选择广告位置"
            >
              <el-option label="全部位置" value=""></el-option>
              <el-option label="首页顶部" value="首页顶部"></el-option>
              <el-option label="右侧边栏" value="右侧边栏"></el-option>
            </el-select>

            <el-button type="primary" @click="fetchStatisticsData">查询数据</el-button>
          </div>

          <!-- 数据概览 -->
          <div class="stats-overview">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-label">总曝光量</div>
                  <div class="stat-value">{{ totalImpressions }}</div>
                  <div :class="impressionsTrend > 0 ? 'up' : 'down'" class="stat-trend">
                    <i v-if="impressionsTrend > 0" class="el-icon-arrow-up"></i>
                    <i v-if="impressionsTrend <= 0" class="el-icon-arrow-down"></i>
                    {{ Math.abs(impressionsTrend) }}%
                  </div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-label">总点击量</div>
                  <div class="stat-value">{{ totalClicks }}</div>
                  <div :class="clicksTrend > 0 ? 'up' : 'down'" class="stat-trend">
                    <i v-if="clicksTrend > 0" class="el-icon-arrow-up"></i>
                    <i v-if="clicksTrend <= 0" class="el-icon-arrow-down"></i>
                    {{ Math.abs(clicksTrend) }}%
                  </div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-label">平均点击率</div>
                  <div class="stat-value">{{ avgCtr }}%</div>
                  <div :class="ctrTrend > 0 ? 'up' : 'down'" class="stat-trend">
                    <i v-if="ctrTrend > 0" class="el-icon-arrow-up"></i>
                    <i v-if="ctrTrend <= 0" class="el-icon-arrow-down"></i>
                    {{ Math.abs(ctrTrend) }}%
                  </div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-label">活跃广告数</div>
                  <div class="stat-value">{{ activeAdsCount }}</div>
                  <div :class="activeAdsTrend > 0 ? 'up' : 'down'" class="stat-trend">
                    <i v-if="activeAdsTrend > 0" class="el-icon-arrow-up"></i>
                    <i v-if="activeAdsTrend <= 0" class="el-icon-arrow-down"></i>
                    {{ Math.abs(activeAdsTrend) }}%
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>

          <!-- 图表展示 -->
          <div class="charts-container">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="chart-item">
                  <h3>曝光量与点击量趋势</h3>
                  <el-card>
                    <canvas id="impressionClickChart" height="300"></canvas>
                  </el-card>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="chart-item">
                  <h3>点击率趋势</h3>
                  <el-card>
                    <canvas id="ctrChart" height="300"></canvas>
                  </el-card>
                </div>
              </el-col>
            </el-row>

            <div class="chart-item" style="margin-top: 20px;">
              <h3>各位置广告效果对比</h3>
              <el-card>
                <canvas id="positionComparisonChart" height="300"></canvas>
              </el-card>
            </div>
          </div>

          <!-- 广告数据列表 -->
          <div class="stats-table">
            <h3>广告详细数据</h3>
            <el-table
                :data="adsStatsTableData"
                border
                style="width: 100%; margin-top: 15px;"
            >
              <el-table-column
                  align="center"
                  label="广告ID"
                  prop="id"
                  width="115"
              ></el-table-column>
              <el-table-column
                  label="广告名称"
                  prop="name"
                  width="260"
                  align="center"
              ></el-table-column>
              <el-table-column
                  align="center"
                  label="类型"
                  prop="adTypeDescription"
                  width="130"
              ></el-table-column>
              <el-table-column
                  align="center"
                  label="位置"
                  prop="position"
                  width="160"
              ></el-table-column>
              <el-table-column
                  align="center"
                  label="曝光量"
                  prop="impressions"
                  width="140"
              ></el-table-column>
              <el-table-column
                  align="center"
                  label="点击量"
                  prop="clicks"
                  width="140"
              ></el-table-column>
              <el-table-column
                  align="center"
                  label="点击率(%)"
                  prop="ctr"
                  width="140"
              ></el-table-column>
              <el-table-column
                  align="center"
                  label="操作"
                  width="160"
              >
                <template #default="scope">
                  <el-button
                      size="small"
                      @click="viewAdDetails(scope.row)"
                  >
                    详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>

      <!-- 创建/编辑广告弹窗 -->
      <el-dialog
          v-model="editDialog.visible"
          :title="editDialog.title"
          width="800px"
          @close="cancelEdit"
      >
        <el-form
            ref="editFormRef"
            :model="editForm"
            :rules="adRules"
            label-width="120px"
        >
          <el-form-item label="所属公司" prop="advertiserId">
            <el-select
                v-model="editForm.advertiserId"
                placeholder="请选择广告商"
                style="width: 100%"
                filterable
                :loading="merchantLoading"
            >
              <el-option
                  v-for="merchant in merchantTableData"
                  :key="merchant.id"
                  :label="merchant.name"
                  :value="merchant.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="广告名称" prop="name">
            <el-input v-model="editForm.name" placeholder="请输入广告名称"></el-input>
          </el-form-item>

          <el-form-item label="广告类型" prop="adTypeDescription">
            <el-radio-group v-model="editForm.adTypeDescription">
              <el-radio label="信息流广告">信息流广告</el-radio>
              <el-radio label="侧边栏广告">侧边栏广告</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="展示位置" prop="position">
            <el-select v-model="editForm.position" placeholder="请选择展示位置">
              <el-option label="首页顶部" value="首页顶部"></el-option>
              <el-option label="右侧边栏" value="右侧边栏"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
                v-model="editForm.startTime"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择开始时间"
                type="datetime"
                value-format="YYYY-MM-DDTHH:mm:ss"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
                v-model="editForm.endTime"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择结束时间"
                type="datetime"
                value-format="YYYY-MM-DDTHH:mm:ss"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="跳转链接" prop="linkUrl">
            <el-input v-model="editForm.linkUrl" placeholder="请输入广告点击跳转链接"></el-input>
          </el-form-item>

          <el-form-item label="广告图片" prop="imageUrl">
            <el-input
                v-model="editForm.imageUrl"
                placeholder="请输入图片URL或上传图片"
                style="margin-bottom: 10px;"
                @blur="validateImageUrl"
            >
              <template #append>
                <el-button @click="testImageUrl">测试链接</el-button>
              </template>
            </el-input>

            <div v-if="editForm.imageUrl" style="margin-top: 10px;">
              <img
                  :src="editForm.imageUrl"
                  alt="广告图片预览"
                  style="max-width: 200px; max-height: 150px; border: 1px solid #ddd;"
                  @error="handleImageError"
              >
              <div style="margin-top: 5px; font-size: 12px; color: #666;">
                图片预览
              </div>
            </div>

            <div v-else style="margin-top: 10px; color: #999; font-size: 12px;">
              请输入有效的图片URL链接
            </div>
          </el-form-item>

          <el-form-item label="广告内容" prop="description">
            <el-input
                v-model="editForm.description"
                placeholder="请输入广告描述内容"
                :rows="4"
                type="textarea"
            ></el-input>
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="cancelEdit">取消</el-button>
          <el-button :loading="editDialog.loading" type="primary" @click="submitEditForm">
            {{ editDialog.type === 'create' ? '创建广告' : '更新广告' }}
          </el-button>
        </template>
      </el-dialog>

      <!-- 广告审核页面 -->
      <div v-show="activeTab === 'review'" class="tab-content">
        <el-card class="ad-card">
          <div slot="header">
            <div style="display: flex; justify-content: space-between; align-items: center;">
            <h2>广告审核</h2>
              <el-button type="primary" @click="handleCreateAd">
                <i class="el-icon-plus"></i>
                创建广告
              </el-button>
            </div>
          </div>

          <div class="filter-bar">
            <el-input
                v-model="reviewFilter.keyword"
                class="search-input"
                placeholder="搜索广告名称"
                prefix-icon="Search"
                @keyup.enter="fetchReviewData"
            ></el-input>
            <el-select
                v-model="reviewFilter.status"
                class="status-select"
                placeholder="选择审核状态"
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="待审核" value="1"></el-option>
              <el-option label="已通过" value="2"></el-option>
              <el-option label="已驳回" value="4"></el-option>
              <el-option label="已完成" value="5"></el-option>
            </el-select>
            <el-button type="primary" @click="searchAuditData">搜索</el-button>
            <el-button @click="resetReviewFilter">重置</el-button>
          </div>

          <el-table
              :data="reviewTableData"
              border
              style="width: 100%; margin-top: 15px;"
          >
            <el-table-column
                align="center"
                label="ID"
                prop="id"
                width="50"
            ></el-table-column>
            <el-table-column
                align="center"
                label="所属公司"
                prop="advertiserName"
                width="110"
            >
            </el-table-column>
            <el-table-column
                label="广告名称"
                prop="name"
                width="200"
            ></el-table-column>
            <el-table-column
                align="center"
                label="展示位置"
                prop="position"
                width="140"
            ></el-table-column>
            <el-table-column
                align="center"
                label="提交时间"
                prop="submitTime"
                width="220"
            ></el-table-column>
            <el-table-column
                align="center"
                label="状态"
                prop="adStatusDescription"
                width="140"
            >
            </el-table-column>
            <!-- 操作列 -->
            <el-table-column
                align="center"
                label="操作"
                width="400"
            >
              <template #default="scope">
                <div class="action-buttons">
                  <!-- 查看详情按钮 - 始终显示 -->
                  <el-button
                      size="small"
                      @click="handleReviewDetail(scope.row)"
                      class="action-btn"
                  >
                    查看详情
                  </el-button>

                  <!-- 编辑按钮 -->
                  <el-button
                      size="small"
                      :type="scope.row.adStatus === 1 ? 'primary' : 'info'"
                      @click="handleEdit(scope.row)"
                      class="action-btn"
                  >
                    编辑
                  </el-button>

                  <!-- 删除按钮 -->
                  <el-button
                      size="small"
                      type="danger"
                      @click="handleDelete(scope.row)"
                      class="action-btn"
                  >
                    删除
                  </el-button>

                  <!-- 审核通过按钮 -->
                  <el-button
                      size="small"
                      type="success"
                      :disabled="scope.row.adStatusId !== 1"
                      @click="handleApprove(scope.row)"
                      class="action-btn"
                  >
                    通过
                  </el-button>

                  <!-- 驳回按钮 -->
                  <el-button
                      size="small"
                      type="warning"
                      :disabled="scope.row.adStatusId !== 1"
                      @click="handleReject(scope.row)"
                      class="action-btn"
                  >
                    驳回
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
                :current-page="currentPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 50]"
                :total="totalReviewItems"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="reviewPagination.handleSizeChange"
                @current-change="reviewPagination.handleCurrentChange"
            ></el-pagination>
          </div>
        </el-card>
      </div>


      <!-- 广告商页面 -->
      <div v-show="activeTab === 'merchant'" class="tab-content">
        <el-card class="ad-card">
          <div slot="header">
            <h2>广告商管理</h2>
          </div>

          <!-- 操作栏 -->
          <div class="operation-bar">
            <el-button type="primary" @click="handleAddMerchant">
              <i class="el-icon-plus"></i>
              新增广告商
            </el-button>

            <div class="filter-bar">
              <el-input
                  v-model="merchantFilter.keyword"
                  class="search-input"
                  clearable
                  placeholder="搜索广告商名称"
                  prefix-icon="Search"
              ></el-input>
              <el-select
                  v-model="merchantFilter.status"
                  class="status-select"
                  clearable
                  placeholder="选择状态"
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="2"></el-option>
              </el-select>
              <el-button
                  type="primary"
                  @click="() => { merchantPagination.currentPage = 1; fetchMerchantData(); }"
              >
                搜索
              </el-button>
              <el-button @click="resetMerchantFilter">重置</el-button>
            </div>
          </div>

          <!-- 广告商表格 -->
          <el-table
              v-loading="merchantLoading"
              :data="merchantTableData"
              border
              style="width: 100%; margin-top: 15px;"
          >
            <el-table-column
                align="center"
                label="ID"
                prop="id"
                width="80"
            ></el-table-column>
            <el-table-column
                label="广告商名称"
                prop="name"
                width="130"
            ></el-table-column>
            <el-table-column
                label="联系人"
                prop="contactPerson"
                width="100"
            ></el-table-column>
            <el-table-column
                label="联系电话"
                prop="contactPhone"
                width="150"
            ></el-table-column>
            <el-table-column
                label="邮箱"
                prop="contactEmail"
                width="200"
            ></el-table-column>
            <el-table-column
                align="center"
                label="账户余额"
                prop="balance"
                width="120"
            >
              <template #default="scope">
                ¥{{ scope.row.balance }}
              </template>
            </el-table-column>
            <el-table-column
                align="center"
                label="状态"
                prop="status"
                width="100"
            >
              <template #default="scope">
                <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
                <el-tag v-else-if="scope.row.status === 2" type="danger">禁用</el-tag>
                <el-tag v-else-if="scope.row.status === 3" type="danger">已删除</el-tag>
              </template>
            </el-table-column>
            <el-table-column
                align="center"
                label="创建时间"
                prop="createdAt"
                width="180"
            ></el-table-column>
            <el-table-column
                align="center"
                fixed="right"
                label="操作"
                width="200"
            >
              <template #default="scope">
                <el-button
                    size="small"
                    @click="handleEditMerchant(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                    :type="scope.row.status === 1 ? 'warning' : 'success'"
                    size="small"
                    @click="handleToggleStatus(scope.row)"
                >
                  {{ scope.row.status === 1 ? '禁用' : '启用' }}
                </el-button>
                <el-button
                    size="small"
                    type="danger"
                    @click="handleDeleteMerchant(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
                v-model:current-page="merchantPagination.currentPage"
                v-model:page-size="merchantPagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="merchantPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="merchantPaginationHandler.handleSizeChange"
                @current-change="merchantPaginationHandler.handleCurrentChange"
            ></el-pagination>
          </div>
        </el-card>

        <!-- 新增/编辑广告商对话框 -->
        <el-dialog
            v-model="merchantDialog.visible"
            :name="merchantDialog.name"
            width="600px"
            @close="handleMerchantDialogClose"
        >
          <el-form
              ref="merchantFormRef"
              :model="merchantForm"
              :rules="merchantRules"
              label-width="100px"
          >
            <el-form-item label="广告商名称" prop="name">
              <el-input v-model="merchantForm.name" placeholder="请输入广告商名称"></el-input>
            </el-form-item>

            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="merchantForm.contactPerson" placeholder="请输入联系人姓名"></el-input>
            </el-form-item>

            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="merchantForm.contactPhone" placeholder="请输入联系电话"></el-input>
            </el-form-item>

            <el-form-item label="邮箱" prop="contactEmail">
              <el-input v-model="merchantForm.contactEmail" placeholder="请输入邮箱地址"></el-input>
            </el-form-item>

            <el-form-item label="账户余额" prop="balance">
              <el-input-number
                  v-model="merchantForm.balance"
                  :min="0"
                  :precision="2"
                  :step="1000"
                  controls-position="right"
                  style="width: 100%"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="merchantForm.status">
                <el-radio label="active">启用</el-radio>
                <el-radio label="inactive">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>

          <template #footer>
            <el-button @click="merchantDialog.visible = false">取消</el-button>
            <el-button :loading="merchantDialog.loading" type="primary" @click="submitMerchantForm">
              确定
            </el-button>
          </template>
        </el-dialog>
      </div>


    </div>
  </div>
</template>

<script setup>
import {nextTick, onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Chart, registerables} from 'chart.js';
import http from "@/request/http.js";
import router from "@/router/index.js";


//日期时间格式
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-');
};

// 活跃菜单和标签
const activeMenu = ref('statistics');
const activeTab = ref('statistics');

// 页面标题映射
const pageTitles = {
  statistics: '广告数据统计',
  review: '广告审核',
  merchant: '广告商管理'
};

// 计算当前页面标题
const pageTitle = ref(pageTitles[activeTab.value]);

// 新增广告 表单数据
const adForm = reactive({
  id: null,
  name: '',
  adType: '',
  adTypeDescription: '',
  position: '',
  startTime: '',
  endTime: '',
  linkUrl: '',
  imageUrl: '',
  description: '',
  status: 1
});

// 广告表单验证规则
const adRules = reactive({
  name: [
    {required: true, message: '请输入广告名称', trigger: 'blur'},
    {max: 50, message: '广告名称不能超过50个字符', trigger: 'blur'}
  ],
  adTypeDescription: [
    {required: true, message: '请选择广告类型', trigger: 'change'}
  ],
  position: [
    {required: true, message: '请选择展示位置', trigger: 'change'}
  ],
  startTime: [
    {required: true, message: '请选择开始时间', trigger: 'change'}
  ],
  endTime: [
    {required: true, message: '请选择结束时间', trigger: 'change'}
  ],
  linkUrl: [
    {required: true, message: '请输入跳转链接', trigger: 'blur'},
    {type: 'url', message: '请输入正确的URL格式', trigger: 'blur'}
  ],
  imageUrl: [
    {required: true, message: '请上传广告图片', trigger: 'change'}
  ],
  description: [
    {required: true, message: '请输入广告内容', trigger: 'blur'},
    {max: 500, message: '广告内容不能超过500个字符', trigger: 'blur'}
  ],
  budget: [
    {required: true, message: '请输入广告预算', trigger: 'blur'},
    {type: 'number', min: 0, message: '预算不能为负数', trigger: 'blur'}
  ],
  displayDuration: [
    {required: true, message: '请输入展示时长', trigger: 'blur'},
    {type: 'number', min: 0, message: '时长不能为负数', trigger: 'blur'}
  ]
});

// 广告商页面数据
const merchantFilter = reactive({
  keyword: '',
  status: ''
});


//分页
const merchantPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});


const merchantDialog = reactive({
  visible: false,
  name: '新增广告商',
  loading: false,
  type: 'add'
});

//广告商表格
const merchantForm = reactive({
  id: null,
  name: '',
  contactPerson: '',
  contactPhone: '',
  contactEmail: '',
  balance: 0,
  status: ''
});

//广告商验证
const merchantRules = reactive({
  name: [
    {required: true, message: '请输入广告商名称', trigger: 'blur'},
    {max: 50, message: '广告商名称不能超过50个字符', trigger: 'blur'}
  ],
  contactPerson: [
    {required: true, message: '请输入联系人姓名', trigger: 'blur'}
  ],
  contactPhone: [
    {required: true, message: '请输入联系电话', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ],
  contactEmail: [
    {required: true, message: '请输入邮箱地址', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur'}
  ],
  balance: [
    {required: true, message: '请输入账户余额', trigger: 'blur'}
  ],
  status: [
    {required: true, message: '请选择状态', trigger: 'change'}
  ]
});

const merchantFormRef = ref();


// 审核过滤条件
const reviewFilter = reactive({
  keyword: '',
  status: ''
});

// 审核表格数据
const reviewTableData = ref([]);

//获取审核数据
const fetchReviewData = async () => {
  const response = await http.get('/ads', {
    params: {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      name: reviewFilter.keyword,
      adStatus: reviewFilter.status
    }
  });

  console.log('API响应数据:', response)
  if (response.code === 200) {
    reviewTableData.value = response.data.list.map(ad => ({
      id: ad.id,
      advertiserName: ad.advertiserName,
      name: ad.name,
      adTypeDescription: ad.adTypeDescription,
      position: ad.position,
      submitTime: formatDateTime(ad.submitTime),
      adStatusId: ad.adStatusId,
      adStatusDescription: ad.adStatusDescription,
      description: ad.description,
      budget: ad.budget,
      displayDuration: ad.displayDuration,
      linkUrl: ad.linkUrl,
      imageUrl: ad.imageUrl,
      startTime: ad.startTime,
      endTime: ad.endTime,
      rejectReason: ad.rejectReason
    }));
    totalReviewItems.value = response.data.total
  } else {
    ElMessage.error("获取失败" + response.msg)
  }
};

//创建广告
const handleCreateAd = async () => {
  await fetchMerchantData(true);
  // 确保广告商数据已加载
  if (merchantTableData.value.length === 0) {
    ElMessage.warning('没有可用的广告商，请先启用广告商');
  }
  editDialog.type = 'create';
  editDialog.title = '创建新广告';
  editDialog.visible = true;

  // 重置表单
  resetEditForm();
};




// 编辑广告对话框
const editDialog = reactive({
  visible: false,
  loading: false,
  title: '编辑广告',
  type: 'edit'
});

const editFormRef = ref();

// 编辑表单数据
const editForm = reactive({
  id: null,
  name: '',
  adTypeDescription: '',
  position: '',
  description: '',
  linkUrl: '',
  imageUrl: '',
  startTime: '',
  endTime: '',
  budget: 0,
  displayDuration: 0,
  advertiserId: null,
  adStatus: 1,
  adStatusDescription: '待审核'
});

//编辑广告审核 数据
const handleEdit = (row) => {
  editDialog.type = 'edit';
  editDialog.title = `编辑广告 - ${row.name}`;
  editDialog.visible = true;

  Object.assign(editForm, {
    id: row.id,
    name: row.name,
    adTypeDescription: row.adTypeDescription,
    position: row.position,
    description: row.description,
    linkUrl: row.linkUrl,
    imageUrl: row.imageUrl,
    startTime: row.startTime,
    endTime: row.endTime,
    advertiserId: row.advertiserId,
    adStatus: row.adStatusId || 1,
    adStatusDescription: row.adStatusDescription || '待审核'
  });
};


// 重置编辑表单
const resetEditForm = () => {
  Object.assign(editForm, {
    id: null,
    name: '',
    adTypeDescription: '',
    position: '',
    description: '',
    linkUrl: '',
    imageUrl: '',
    startTime: '',
    endTime: '',
    budget: 0,
    displayDuration: 0,
    advertiserId: null,
    adStatus: 1,
    adStatusDescription: '待审核'
  });


  if (editFormRef.value) {
    editFormRef.value.clearValidate();
  }
};



// 提交广告表单
const adFormRef = ref();
const isEdit = ref(false);
const adTypeMapping = {
  '信息流广告': 1,
  '侧边栏广告': 2
};


// 提交广告表单
const submitEditForm = async () => {
  const valid = await editFormRef.value.validate();
  if (!valid) return;

  editDialog.loading = true;

  const submitData = {
    id: editForm.id,
    name: editForm.name,
    adTypeDescription: editForm.adTypeDescription,
    adType: adTypeMapping[editForm.adTypeDescription] || 1,
    position: editForm.position,
    description: editForm.description,
    linkUrl: editForm.linkUrl,
    imageUrl: editForm.imageUrl,
    startTime: editForm.startTime,
    endTime: editForm.endTime,
    budget: editForm.budget,
    displayDuration: editForm.displayDuration,
    advertiserId: editForm.advertiserId,
    adStatus: 1,
    adStatusDescription: '待审核'
  };

  let response;
  if (editDialog.type === 'edit') {
    // 编辑广告
    response = await http.post('/ads/updateAd', submitData);
  } else {
    // 创建新广告
    delete submitData.id;
    response = await http.post('/ads/createAd', submitData);
  }

  if (response.code === 200) {
    const successMessage = editDialog.type === 'edit' ? '广告更新成功' : '广告创建成功';
    ElMessage.success(successMessage);
    editDialog.visible = false;
    await fetchReviewData(); // 刷新审核列表
    resetEditForm(); // 重置表单
  } else {
    const errorMessage = editDialog.type === 'edit' ? '广告更新失败' : '广告创建失败';
    ElMessage.error(response.msg || errorMessage);
  }
};

// 验证图片URL
const validateImageUrl = () => {
  if (!editForm.imageUrl) return;

  // 简单的URL验证
  const urlPattern = /^(https?:\/\/.*\.(?:png|jpg|jpeg|gif|webp))$/i;
  if (!urlPattern.test(editForm.imageUrl)) {
    ElMessage.warning('请输入有效的图片URL（支持png、jpg、jpeg、gif、webp格式）');
  }
};

// 测试图片链接
const testImageUrl = async () => {
  if (!editForm.imageUrl) {
    ElMessage.warning('请输入图片URL');
    return;
  }

  try {
    const img = new Image();
    img.onload = () => {
      ElMessage.success('图片链接有效');
    };
    img.onerror = () => {
      ElMessage.error('图片链接无效或无法访问');
    };
    img.src = editForm.imageUrl;
  } catch (error) {
    ElMessage.error('测试图片链接时出错');
  }
};

// 处理图片加载错误
const handleImageError = (event) => {
  console.error('图片加载失败:', editForm.imageUrl);
  ElMessage.error('图片加载失败，请检查URL是否正确');
};

// 取消编辑对话框
const cancelEdit = () => {
  editDialog.visible = false;
  editDialog.loading = false;
  resetEditForm();
};

// 处理删除广告
const handleDelete = async (row) => {
  await ElMessageBox.confirm(
      `确定要删除广告 "${row.name}" 吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error',
        confirmButtonClass: 'el-button--danger'
      }
  );

  // 调用删除API
  const response = await http.delete(`/ads?id=${row.id}`);

  if (response.code === 200) {
    ElMessage.success('广告删除成功');

    // 刷新审核列表数据
    await fetchReviewData();

    // 如果是统计页面，也刷新统计数据
    if (activeTab.value === 'statistics') {
      fetchStatisticsData();
    }
  } else {
    ElMessage.error(response.msg);
  }
};


//广告商表格数据
const merchantTableData = ref([])
const merchantLoading = ref(false);

// 获取广告商数据
const fetchMerchantData = async (forCreateAd = false) => {
  const params = {
    currentPage: merchantPagination.currentPage,
    pageSize: merchantPagination.pageSize,
    name: merchantFilter.keyword,
  }
  if (forCreateAd) {
    params.status = 1; // 创建广告时只看启用的
  } else {
    // 关键修复：无论状态是否为空，都显式处理参数
    if (merchantFilter.status !== '' && merchantFilter.status !== null) {
      params.status = merchantFilter.status;
    } else {
      // 明确不传递status参数，让后端返回所有非删除状态
      delete params.status;
    }
  }
  const response = await http.get('/ads/advertiser', {params});

  if (response.code === 200) {
    merchantTableData.value = response.data.list.map(advertiser => ({
      id: advertiser.id,
      name: advertiser.name,
      contactPerson: advertiser.contactPerson,
      contactPhone: advertiser.contactPhone,
      contactEmail: advertiser.contactEmail,
      balance: advertiser.balance,
      status: advertiser.status,
      createdAt: advertiser.createdAt,
      updatedAt: advertiser.updatedAt
    }));
    merchantPagination.total = response.data.total;
  } else {
    ElMessage.error('获取广告商数据失败，' + response.msg);
  }
}


//重置广告商搜索数据
const resetMerchantFilter = () => {
  merchantFilter.keyword = '';
  merchantFilter.status = '';
  merchantPagination.currentPage = 1;
  fetchMerchantData();

};


//搜索广告数据
const searchAuditData = () => {
  currentPage.value = 1;
  fetchReviewData();
}

//重置广告搜索数据
const resetReviewFilter = () => {
  reviewFilter.keyword = '';
  reviewFilter.status = '';
  currentPage.value = 1;
  pageSize.value = 10;
  fetchReviewData();
};

//新增广告商表单
const handleAddMerchant = () => {

  merchantDialog.type = 'add';
  merchantDialog.name = '新增广告商';
  merchantDialog.visible = true;
  resetMerchantForm();
};

//重置表单的方法
const resetMerchantForm = () => {
  Object.assign(merchantForm, {
    id: null,
    name: '',
    contactPerson: '',
    contactPhone: '',
    contactEmail: '',
    balance: 0,
    status: 1 // 默认启用状态
  });

  // 清除表单验证
  if (merchantFormRef.value) {
    merchantFormRef.value.clearValidate();
  }
};

//编辑广告商表单
const handleEditMerchant = (row) => {
  merchantDialog.type = 'edit';
  merchantDialog.name = '编辑广告商';
  merchantDialog.visible = true;

  // 填充表单数据
  Object.assign(merchantForm, {
    id: row.id,
    name: row.name,
    contactPerson: row.contactPerson,
    contactPhone: row.contactPhone,
    contactEmail: row.contactEmail,
    balance: row.balance,
    status: row.status === 1 ? 'active' : 'inactive'
  });
};

// 处理状态切换
const handleToggleStatus = async (row) => {
  const newStatus = row.status === 1 ? 2 : 1; // 1=启用, 2=禁用
  const action = row.status === 1 ? '禁用' : '启用';
  await ElMessageBox.confirm(`确定要${action}该广告商吗？`, '操作确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });

  // 调用API更新状态
  const response = await http.post(`/ads/disableAdvertiser?id=${row.id}&status=${newStatus}`);

  if (response.code === 200) {
    ElMessage.success(`广告商已${action}`);
    await fetchMerchantData(); // 刷新列表
  } else {
    ElMessage.error(response.msg || `${action}失败`);
  }
};

//处理删除广告商
const handleDeleteMerchant = async (row) => {
  await ElMessageBox.confirm(
      `确定要删除"${row.name}"广告商吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
  );

  const response = await http.delete(`/ads/advertiser?id=${row.id}`);
  if (response.code === 200) {
    ElMessage.success('广告商删除成功!');
    await fetchMerchantData();
  } else {
    ElMessage.error(response.msg || '删除失败');
  }
};


const submitMerchantForm = async () => {
  const valid = await merchantFormRef.value.validate();
  if (!valid) return;

  merchantDialog.loading = true;

  try {
    // 准备提交数据
    const submitData = {
      name: merchantForm.name,
      contactPerson: merchantForm.contactPerson,
      contactPhone: merchantForm.contactPhone,
      contactEmail: merchantForm.contactEmail,
      balance: merchantForm.balance,
      status: merchantForm.status === 'active' ? 1 : 2
    };

    let response;
    if (merchantDialog.type === 'add') {
      // 新增广告商
      response = await http.post('/ads/advertiser', submitData);
    } else {
      // 编辑广告商
      submitData.id = merchantForm.id;
      response = await http.put('/ads/advertiser', submitData);
    }

    if (response.code === 200) {
      const successMessage = merchantDialog.type === 'add' ? '广告商新增成功' : '广告商修改成功';
      ElMessage.success(successMessage);
      merchantDialog.visible = false;
      await fetchMerchantData(); // 刷新列表
    } else {
      ElMessage.error(response.msg || '操作失败');
    }
  } catch (error) {
    ElMessage.error('操作失败，请重试');
  } finally {
    merchantDialog.loading = false;
  }
};

const handleMerchantDialogClose = () => {
  //关闭对话框时重置表单
  resetMerchantForm();
  merchantFormRef.value?.clearValidate();
};


// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const totalReviewItems = ref(0);


const reviewPagination = {
  handleSizeChange: (val) => {
    pageSize.value = val;
    currentPage.value = 1;
    fetchReviewData();
  },
  handleCurrentChange: (val) => {
    currentPage.value = val;
    fetchReviewData();
  }
}

const merchantPaginationHandler = {
  handleSizeChange: (val) => {
    merchantPagination.pageSize = val;
    merchantPagination.currentPage = 1;
    fetchMerchantData();
  },
  handleCurrentChange: (val) => {
    merchantPagination.currentPage = val;
    fetchMerchantData();
  }
};



// 处理菜单选择
const handleMenuSelect = (index) => {
  activeTab.value = index;
  pageTitle.value = pageTitles[index];

  if (index === 'statistics') {
    nextTick(() => {
      initCharts();
    });
  } else if (index === 'review') {
    fetchReviewData();
  } else if (index === 'merchant') {
    merchantPagination.currentPage = 1;
    fetchMerchantData();
  }
};





// 处理图片上传成功
const handleImageUpload = (response, file, fileList) => {
  // 根据实际后端返回的数据结构调整
  if (response.code === 200) {
    editForm.imageUrl = response.data.url; // 假设返回数据中有url字段
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error('图片上传失败');
  }
};

// 处理审核详情
const handleReviewDetail = (row) => {
  ElMessageBox.alert(`
    <div style="text-align: left;">
      <p><strong>广告ID：</strong>${row.id}</p>
      <p><strong>广告名称：</strong>${row.name}</p>
      <p><strong>所属公司：</strong>${row.advertiserName}</p>
      <p><strong>广告类型：</strong>${row.adTypeDescription}</p>
      <p><strong>展示位置：</strong>${row.position}</p>
      <p><strong>提交时间：</strong>${row.submitTime}</p>
      <p><strong>当前状态：</strong>${row.adStatusDescription}</p>
      <p><strong>广告描述：</strong>${row.description || '无'}</p>
      <p><strong>广告预算：</strong>¥${row.budget || '0'}</p>
      <p><strong>展示时长(秒)：</strong>${row.displayDuration || '0'}</p>
      <p><strong>开始时间：</strong>${formatDateTime(row.startTime) || '未设置'}</p>
      <p><strong>结束时间：</strong>${formatDateTime(row.endTime) || '未设置'}</p>
      <p><strong>跳转链接：</strong>${row.linkUrl || '未设置'}</p>
      ${row.rejectReason ? `<p><strong>驳回原因：</strong>${row.rejectReason}</p>` : ''}
    </div>
  `, '广告详情', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确定'
  });
};

// 处理审核通过
const handleApprove = async (row) => {
  await ElMessageBox.confirm('确定要通过此广告吗？', '审核确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success'
  })
  // 调用审核通过API
  const response = await http.post('/ads/approveAd', {
    id: row.id,
    adStatus: 2, // 已通过状态
  });
  if (response.code === 200) {
    ElMessage.success('广告审核已通过');
    await fetchReviewData(); // 刷新列表
  } else {
    ElMessage.error(response.msg || '审核操作失败');
  }
};

// 处理审核驳回
const handleReject = async (row) => {
  const {value} = await ElMessageBox.prompt('请输入驳回原因', '驳回原因', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
  const response = await http.post('/ads/rejectAd', {
    id: row.id,
    adStatus: 4, // 已驳回状态
    adStatusDescription: '已驳回',
    rejectReason: value
  });
  if (response.code === 200) {
    ElMessage.success('广告已驳回');
    await fetchReviewData(); // 刷新列表
  } else {
    ElMessage.error(response.msg || '驳回操作失败');
  }
};


// 注册Chart.js组件
Chart.register(...registerables);
// 图表实例引用
const chartInstances = reactive({
  impressionClick: null,
  ctr: null,
  positionComparison: null
});


// 趋势数据
const impressionsTrend = ref(12.5);
const clicksTrend = ref(8.3);
const ctrTrend = ref(-2.1);
const activeAdsTrend = ref(5.2);


// 统计过滤条件
const dateRange = ref([]);
const statsFilter = reactive({
  position: ''
});

// 统计数据
const totalImpressions = ref(0);
const totalClicks = ref(0);
const avgCtr = ref(0);
const activeAdsCount = ref(0);
const impressionsClickChart = ref(null);
const ctrChart = ref(null);
const positionComparisonChart = ref(null);
const adsStatsTableData = ref([]);

// 初始化图表函数
const initCharts = () => {
  // 确保在DOM更新后执行
  nextTick(() => {
    // 先销毁现有图表
    Object.values(chartInstances).forEach(chart => {
      if (chart) {
        chart.destroy();
      }
    });
    fetchStatisticsData();
  });
};

// 获取统计数据
const fetchStatisticsData = async () => {
  if (!dateRange.value || dateRange.value.length === 0) {
    const end = new Date();
    const start = new Date();
    start.setDate(start.getDate() - 6);
    dateRange.value = [
      start.toISOString().split('T')[0],
      end.toISOString().split('T')[0]
    ];
  }
  // 构建请求参数
  const params = {
    startDate: dateRange.value?.[0] || '',
    endDate: dateRange.value?.[1] || '',
    position: statsFilter.position || '',
    //时间戳避免缓存
    _t: new Date().getTime()
  };

  console.log('统计查询参数:', params);

  // 调用后端API获取统计数据
  const response = await http.get('/ads/getAdStatistics', {params});

  if (response.code === 200) {
    const statsData = response.data;
    console.log('统计API返回数据:', statsData);
    console.log('图表数据详情:', statsData.chartData);
    console.log('曝光数据:', statsData.chartData?.impressionData);
    console.log('点击数据:', statsData.chartData?.clickData);
    console.log('日期标签:', statsData.chartData?.dateLabels);

    // 更新概览数据
    totalImpressions.value = statsData.totalImpressions || 0;
    totalClicks.value = statsData.totalClicks || 0;
    avgCtr.value = statsData.avgCtr ? statsData.avgCtr.toFixed(2) : '0.00';
    activeAdsCount.value = statsData.activeAdsCount || 0;

    // 更新趋势数据
    impressionsTrend.value = statsData.impressionsTrend || 0;
    clicksTrend.value = statsData.clicksTrend || 0;
    ctrTrend.value = statsData.ctrTrend || 0;
    activeAdsTrend.value = statsData.activeAdsTrend || 0;

    // 更新表格数据
    adsStatsTableData.value = statsData.adDetails || [];

    // 确保DOM更新后再渲染图表
    await nextTick(() => {
      updateCharts(statsData.chartData);
    });
  } else {
    ElMessage.error('获取统计数据失败');
  }
};


// 更新图表数据
const updateCharts = (chartData) => {
  console.log('更新图表数据:', chartData);
  // 销毁现有图表实例
  Object.values(chartInstances).forEach(chart => {
    if (chart) chart.destroy();
  });

  // 曝光量与点击量趋势图
  const icCtx = document.getElementById('impressionClickChart')?.getContext('2d');
  if (icCtx) {
    chartInstances.impressionClick = new Chart(icCtx, {
      type: 'line',
      data: {
        labels: chartData.dateLabels,
        datasets: [
          {
            label: '曝光量',
            data: chartData.impressionData,
            borderColor: '#409EFF',
            backgroundColor: 'rgba(64, 158, 255, 0.1)',
            tension: 0.3,
            fill: true
          },
          {
            label: '点击量',
            data: chartData.clickData,
            borderColor: '#67C23A',
            backgroundColor: 'rgba(103, 194, 58, 0.1)',
            tension: 0.3,
            fill: true
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'top'
          }
        },
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    });
  }

  // 点击率趋势图
  const ctrCtx = document.getElementById('ctrChart')?.getContext('2d');
  if (ctrCtx && chartData.ctrData) {
    chartInstances.ctr = new Chart(ctrCtx, {
      type: 'line',
      data: {
        labels: chartData.dateLabels,
        datasets: [
          {
            label: '点击率(%)',
            data: chartData.ctrData,
            borderColor: '#E6A23C',
            backgroundColor: 'rgba(230, 162, 60, 0.1)',
            tension: 0.3,
            fill: true
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'top'
          }
        },
        scales: {
          y: {
            beginAtZero: true,
            min: 0
          }
        }
      }
    });
  }

  // 各位置广告效果对比图
  const positionCtx = document.getElementById('positionComparisonChart')?.getContext('2d');
  if (positionCtx) {
    generatePositionComparisonChart(positionCtx);
  }
};


// 生成位置对比图表
const generatePositionComparisonChart = (ctx) => {
  if (!adsStatsTableData.value || adsStatsTableData.value.length === 0) {
    return;
  }

  // 按位置分组统计
  const positionStats = {};
  adsStatsTableData.value.forEach(ad => {
    const position = ad.position || '未知位置';
    if (!positionStats[position]) {
      positionStats[position] = {
        impressions: 0,
        clicks: 0,
        count: 0
      };
    }
    positionStats[position].impressions += parseInt(ad.impressions) || 0;
    positionStats[position].clicks += parseInt(ad.clicks) || 0;
    positionStats[position].count += 1;
  });

  // 计算每个位置的点击率
  Object.keys(positionStats).forEach(position => {
    const stats = positionStats[position];
    stats.ctr = stats.impressions > 0 ? (stats.clicks / stats.impressions * 100) : 0;
  });

  const positions = Object.keys(positionStats);
  const impressionsData = positions.map(pos => positionStats[pos].impressions);
  const clicksData = positions.map(pos => positionStats[pos].clicks);
  const ctrData = positions.map(pos => parseFloat(positionStats[pos].ctr.toFixed(2)));

  chartInstances.positionComparison = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: positions,
      datasets: [
        {
          label: '曝光量',
          data: impressionsData,
          backgroundColor: 'rgba(64, 158, 255, 0.7)'
        },
        {
          label: '点击量',
          data: clicksData,
          backgroundColor: 'rgba(103, 194, 58, 0.7)'
        },
        {
          label: '点击率(%)',
          data: ctrData,
          backgroundColor: 'rgba(230, 162, 60, 0.7)',
          yAxisID: 'y1'
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'top'
        }
      },
      scales: {
        y: {
          type: 'linear',
          display: true,
          position: 'left',
          title: {
            display: true,
            text: '数量'
          }
        },
        y1: {
          type: 'linear',
          display: true,
          position: 'right',
          title: {
            display: true,
            text: '点击率(%)'
          },
          min: 0,
          grid: {
            drawOnChartArea: false
          }
        }
      }
    }
  });
};

// 查看广告详情
const viewAdDetails = (row) => {
  ElMessage.info(`查看广告 ${row.id} 的详细数据`);
};



// 页面挂载时初始化
onMounted(() => {
  // 设置默认日期范围为近7天
  const end = new Date();
  const start = new Date();
  start.setDate(start.getDate() - 6);
  dateRange.value = [
    start.toISOString().split('T')[0],
    end.toISOString().split('T')[0]
  ];

  // 初始化数据统计
  fetchStatisticsData();

  // 预加载其他标签页数据
  fetchMerchantData();
});

// 图片上传相关函数
const handleUploadError = (error, file, fileList) => {
  ElMessage.error('图片上传失败');
  console.error('上传错误:', error);
};

const handleFileRemove = (file, fileList) => {
  console.log('文件被移除:', file);
  // 可以在这里处理文件移除后的逻辑
};

const beforeImageUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPGOrPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

</script>

<style scoped>
.ad-management-layout {
  display: flex;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.sidebar {
  width: 250px;
  background-color: #0f172a; /* 深蓝灰色作为主背景 */
  color: #e2e8f0; /* 浅灰色文字 */
  min-height: 100vh;
  transition: all 0.3s ease;
}

.sidebar-header {
  padding: 20px;
  background-color: #1e293b; /* 稍浅的蓝色作为头部背景 */
  border-bottom: 1px solid #334155; /* 统一的分隔线颜色 */
}

.sidebar-header h2 {
  margin: 0;
  color: #f8fafc; /* 更亮的文字颜色突出标题 */
  font-size: 18px;
  text-align: center;
}

.sidebar-menu {
  border: none;
  background-color: transparent;
}

.sidebar-menu :deep(.el-menu-item),
.sidebar-menu :deep(.el-sub-menu__title) {
  color: #bfbfbf;
}

/* 统一菜单项样式 */
.sidebar-menu :deep(.el-menu-item),
.sidebar-menu :deep(.el-sub-menu__title) {
  color: #94a3b8; /* 统一的默认文字颜色 */
  background-color: #0f172a; /* 统一背景色 */
  height: 50px;
  line-height: 50px;
  padding-left: 30px !important;
  transition: all 0.2s ease;
}

/* 悬停状态样式 */
.sidebar-menu :deep(.el-menu-item:hover),
.sidebar-menu :deep(.el-sub-menu__title:hover) {
  background-color: #1e293b; /* 悬停时稍亮的背景 */
  color: #f8fafc; /* 悬停时文字变白 */
}


/* 激活状态样式 */
.sidebar-menu :deep(.el-menu-item.is-active) {
  background-color: #3b82f6; /* 统一的蓝色激活背景 */
  color: #ffffff; /* 激活状态文字颜色 */
}

/* 子菜单样式 */
.sidebar-menu :deep(.el-sub-menu .el-menu) {
  background-color: #1e293b; /* 子菜单背景色与主菜单悬停色一致 */
}

.sidebar-menu :deep(.el-sub-menu .el-menu-item) {
  padding-left: 50px !important; /* 子菜单缩进更大 */
}

/* 箭头颜色调整 */
.sidebar-menu :deep(.el-sub-menu__icon-arrow) {
  color: #94a3b8;
}

.sidebar-menu :deep(.el-sub-menu__title:hover .el-sub-menu__icon-arrow) {
  color: #f8fafc;
}

.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  color: #1f2329;
  margin: 0;
}

.content-area {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.ad-card {
  margin-top: 15px;
}

.ad-form {
  margin-top: 20px;
}

.filter-bar {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.search-input {
  width: 300px;
}

.status-select {
  width: 180px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.stats-filter {
  display: flex;
  gap: 15px;
  margin-top: 15px;
  align-items: center;
}

.position-select {
  width: 200px;
}

.stats-overview {
  margin-top: 20px;
}

.stat-item {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  text-align: center;
}

.stat-label {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1f2329;
  margin-bottom: 5px;
}

.stat-trend {
  font-size: 13px;
}

.stat-trend.up {
  color: #67c23a;
}

.stat-trend.down {
  color: #f56c6c;
}

.charts-container {
  margin-top: 30px;
}

.chart-item h3 {
  font-size: 16px;
  margin-bottom: 10px;
  color: #1f2329;
}

.stats-table {
  margin-top: 30px;
}

.stats-table h3 {
  font-size: 16px;
  margin-bottom: 10px;
  color: #1f2329;
}

.tab-content {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}


/* 在组件的样式中添加以下代码 */
.ad-management-layout {
  display: flex;
  min-height: 100vh; /* 确保布局占满整个视口高度 */
}

.sidebar {
  position: fixed; /* 固定定位，使侧边栏不随滚动移动 */
  top: 0;
  left: 0;
  height: 100vh; /* 高度占满整个视口 */
  width: 250px; /* 根据需要调整宽度 */
  overflow-y: auto; /* 当侧边栏内容过长时，允许内部滚动 */
  z-index: 10; /* 确保侧边栏在内容上方 */
}

.main-content {
  margin-left: 250px; /* 与侧边栏宽度保持一致，避免内容被侧边栏遮挡 */
  flex: 1; /* 占据剩余空间 */
}
</style>